package com.gpj.netty.application.netty.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * @className ClientHandler
 * @description 客户端SocketChannel处理器
 * @author GPJ
 * @date 2021/12/7 11:13
 * @version 1.0
 **/
@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {
	/**
	 * 客户端连接服务器成功的回调方法
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.debug("连接服务器成功");

		log.debug("开始请求服务器...");
		ByteBuf buffer = Unpooled.copiedBuffer(("hello server from ["
				+ ctx.channel().localAddress().toString() + "]").getBytes(CharsetUtil.UTF_8));
		ctx.writeAndFlush(buffer);
		log.debug("服务器请求完毕");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		log.debug("开始接收服务器响应...");
		log.info(((ByteBuf) msg).toString(CharsetUtil.UTF_8));
		log.debug("服务器响应接收完毕");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		log.error("服务器异常:{}", cause.getLocalizedMessage());
		ctx.close();
	}
}
